<template>
  <div :class="[`${prefixCls}`]" v-loading="loading">
    <div class="my-account">第三方APP</div>
    <Row :gutter="[10, 10]" >
      <Col :span="24"  class="account-row-item" v-for="item in thirdAccountList" :key="item.idpConnectId">
        <div class="account-label gray-75">
          <div class="account-logo">
            <img :src="item.logo" />
          </div>
          <div class="gray-75 " style="margin-left: 12px; height: 100%">{{ item.name }}</div>
        </div>
        <div>
          <span 
            class="blue-e5 pointer text-base" 
            style="margin-right: 32px" 
            :class="[item.bindStatus ? 'bind-third-text' : '']"
            @click="thirdBind(item)"
          >
            {{ !item.bindStatus ? "绑定" : "解绑" }}
          </span>
        </div>
      </Col>
    </Row>
   
  </div>
  <Empty v-if="thirdAccountList.length == 0"></Empty>
  <ScanQrCodeBind @register="registerScanQrcode" @scan-success="bindThirdAccount" />
</template>
<script lang="ts" setup name="third-bind-setting">
  import { onMounted, ref, reactive, unref } from "vue"
  import {  Empty, Row, Col } from "ant-design-vue"
  import * as apis from "../api"
  import { useUserStore } from "/@/store/modules/user"
  import { useModal } from "/@/components/Modal"
  import { createFromIconfontCN } from "@ant-design/icons-vue"
  import { useGlobSetting } from "/@/hooks/setting"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { Modal } from "ant-design-vue"
  import { useDesign } from "/@/hooks/web/useDesign"
  import ScanQrCodeBind from "./ScanQrCodeBind.vue"

  const { prefixCls } = useDesign("user-tenant-setting-container")
  const IconFont = createFromIconfontCN({
    scriptUrl: "//at.alicdn.com/t/font_2316098_umqusozousr.js",
  })
  const userStore = useUserStore()
  const [registerScanQrcode, { openModal: openScanQrcodeBind }] = useModal()
  //三方账户列表
  const thirdAccountList = ref<any[]>([])
  const loading = ref<boolean>(true)
  const glob = useGlobSetting()
  const { createMessage } = useMessage()
  //windows对象，用于关闭窗口事件
  const windowsIndex = ref<any>("")
  //窗口监听事件
  const receiveMessage = ref<any>("")
  const qrcodeIdpConnect = ["wechatMpQrcode", "wechatMaQrcode"]

  async function initUserDetail() {
    try {
      let values = await apis.listUserThirdAccount()
      thirdAccountList.value = values
    } finally {
      loading.value = false
    }
  }

  /**
   * 三方用户绑定事件
   */
  function thirdBind(data : any) {
    if (!data.bindStatus) {
      onThirdLogin(data)
    } else {
      handleUnBind({ id: data.id }, data.name)
    }
    console.log("绑定解绑事件", data)
  }

  /**
   * 第三方登录
   * @param source
   */
  async function onThirdLogin({ authorizationUrl, name, idpConnectId, type }) {
    if (qrcodeIdpConnect.find(e => e === type)) {
      openScanQrcodeBind(true, { type, name, idpConnectId })
      return
    }

    // let url = setObjToUrlParams(`${glob.domainUrl}${glob.urlPrefix}/auth-service/thirdAuth/authorize/${grantType}`, params)
    //窗口为不空关闭
    console.log("unref(windowsIndex) ::", unref(windowsIndex))
    if (unref(windowsIndex)) {
      //确保只有一个窗口
      windowsIndex.value.close()
      //确保只有一个监听
      window.removeEventListener("message", unref(receiveMessage), false)
    }
    let width = document.body.clientWidth / 1.3
    let height = document.body.clientHeight / 0.5

    await apis.readyBindIdpConnect()

    loading.value = true
    windowsIndex.value = window.open(
      authorizationUrl,
      `登录 ${name}`,
      `height=${height}, width=${width}, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=n o, status=no`
    )
    receiveMessage.value = async function (event) {
      let data = event.data;
      let origin = event.origin;
      if (data?.source === 'react-devtools-content-script') {
        return
      }
      console.log('thirdLoginData', data, origin)
      const { success, msg, data : loginData } = data
      if (!success) {
        cmsFailed()
      } else {
        bindThirdAccount({ ...loginData, idpConnectId  })
      }
    
      window.removeEventListener("message", unref(receiveMessage), false)
      windowsIndex.value = ""
    }
    window.addEventListener("message", unref(receiveMessage), false)
  }

  /**
   * 绑定当前用户
   */
  async function bindThirdAccount(bindInfo) {
    if (!bindInfo) {
      cmsFailed()
      return
    }
    let params = { openId: bindInfo.openId, idpConnectId: bindInfo.idpConnectId }
    await apis.bindIdpConnect(params)
    initUserDetail()
  }

  /**
   * 失败提示信息
   */
  function cmsFailed() {
    createMessage.warning("第三方账号绑定异常")
    return
  }

  /**
   * 删除第三方信息表
   * @param params
   */
  async function handleUnBind(params, text) {
    Modal.confirm({
      title: "解绑 " + text,
      content: "确定要解绑吗",
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        await apis.unbindIdpConnect(params).then((res) => {
          if (res.success) {
            initUserDetail()
            createMessage.success('解绑成功')
          } else {
            createMessage.warning(res.msg)
          }
        })
      },
    })
  }

  onMounted(() => {
    initUserDetail()
  })
</script>
<style lang="less">
  @prefix-cls: ~"@{namespace}-user-tenant-setting-container";
  .@{prefix-cls} {
    padding: 30px 40px 0 20px;
    .account-row-item {
      align-items: center;
      /*begin 兼容暗夜模式*/
      border-bottom: 1px solid @border-color-base;
      /*end 兼容暗夜模式*/
      box-sizing: border-box;
      flex-direction:row;
      justify-content:space-between;
      display: flex;
      height: 71px;
      position: relative;
    }

    .account-label {
      text-align: left;
      display: flex;
      align-items: center;
      width: 200px;
      font-size: 16px;
    }

    .account-logo {
      width: 36px;
      height: 36px;
      overflow: hidden;
      border: 1px solid #e5e6eb;
      border-radius: 4px;
    }

    .bind-third-text {
      color: #ff4d4f !important;
    }

    .gray-75 {
      /*begin 兼容暗夜模式*/
      color: @text-color !important;
      /*end 兼容暗夜模式*/
    }

    .pointer {
      cursor: pointer;
    }

    .blue-e5 {
      color: #1e88e5;
    }

    .phone-margin {
      margin-left: 24px;
      margin-right: 24px;
    }

    .clearfix:after {
      clear: both;
    }

    .clearfix:before {
      content: "";
      display: table;
    }

    .my-account {
      font-size: 17px;
      font-weight: 700 !important;
      /*begin 兼容暗夜模式*/
      color: @text-color !important;
      /*end 兼容暗夜模式*/
      margin-bottom: 20px;
    }
    .item-icon {
      font-size: 16px !important;
    }
  }
</style>
